package cn.ai.shoes.client.controller;

import cn.ai.shoes.client.entity.ComfyuiLog;
import cn.ai.shoes.client.entity.modelvo.UploadImageVo;
import cn.ai.shoes.client.entity.vo.OssUploadLogPageVo;
import cn.ai.shoes.client.entity.vo.OssUploadLogVo;
import cn.ai.shoes.client.service.OssUploadService;
import cn.ai.shoes.client.service.OssUploadLogService;
import cn.ai.shoes.common.constant.GolbalConstants;
import cn.ai.shoes.common.exception.ServiceException;
import cn.ai.shoes.common.exception.constant.GlobalErrorCodeConstants;
import cn.ai.shoes.common.pojo.entity.CommonResult;
import cn.ai.shoes.core.pojo.entity.MyUser;
import cn.ai.shoes.core.service.UserService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jodd.util.StringUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/oss")
@Tag(name = "OSS上传管理", description = "OSS上传管理")
public class OssUploadController {
    @Resource
    private OssUploadService ossUploadService;
    @Resource
    private OssUploadLogService ossUploadLogService;
    @Resource
    private UserService userService;

    @PostMapping("/upload")
    @PreAuthorize(GolbalConstants.RoleConstants.ROLE_MEMBER_ADMIN)
    @Operation(summary = "上传图片", description = "上传图片")
    public CommonResult<?> uploadImage(@RequestParam("image") @Validated @Schema(description = "图片文件", required = true) MultipartFile multipart) {
        return ossUploadService.uploadImage(multipart);
    }

    @PostMapping("/mask")
    @PreAuthorize(GolbalConstants.RoleConstants.ROLE_MEMBER_ADMIN)
    @Operation(summary = "上传蒙版", description = "上传蒙版")
    public CommonResult<?> createMask(
            @RequestParam("image") @Validated @Schema(description = "蒙版图片文件", required = true) MultipartFile multipart,
            @RequestParam("originalId") @Validated @Schema(description = "原始文件id", required = true) Integer originalId) {
        return ossUploadService.uploadMask(multipart, originalId);
    }

    @GetMapping("/feedback")
    @PreAuthorize(GolbalConstants.RoleConstants.ROLE_MEMBER_ADMIN)
    @Operation(summary = "回显图片", description = "回显图片")
    public CommonResult<?> getImage(@Validated Integer imageId) {
        // 该方法本身就是简单调用 service，无需迁移
        return ossUploadService.feedback(imageId);
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询OSS上传日志")
    public CommonResult<?> pageImageLog(OssUploadLogPageVo pageVo) {
        MyUser user =null;
        IPage<OssUploadLogVo> page =null;
        //查询用户信息
        if (StringUtil.isNotEmpty(pageVo.getUid())) {
            user = userService.selectOneByUid(pageVo.getUid());
        }else{
            return CommonResult.error(GlobalErrorCodeConstants.UID_NOT_EXIST);
        }
        //判断用户不存在
        if (user == null) {
            return CommonResult.error(GlobalErrorCodeConstants.USER_NOT_FOUND);
        }
        //判断用户不是管理员
        if (!user.isAdmin()) {
            //设置用户名
            if (user.getUsername()!= null) {
                pageVo.setUserId(Long.valueOf(user.getId()));
            } else {
                return CommonResult.error(GlobalErrorCodeConstants.USER_NOT_EXIST);
            }
        }
        page = ossUploadLogService.pageOssUploadLogs(pageVo);
        return CommonResult.success(page);
    }

    @GetMapping("/view")
    @PreAuthorize(GolbalConstants.RoleConstants.ROLE_MEMBER_ADMIN)
    @CrossOrigin(origins = "${cors.allowed.origins}")
    @Operation(summary = "回显图片二进制流", description = "根据imageId返回图片二进制流")
    public ResponseEntity<byte[]> viewImage(@RequestParam Integer imageId) {
        // 1. 查找图片日志
        var ossUploadLog = ossUploadLogService.getById(imageId);
        if (ossUploadLog == null || ossUploadLog.getOssPath() == null) {
            throw new ServiceException(GlobalErrorCodeConstants.IMAGE_NOT_FOUND);
        }
        // 2. 获取图片输入流
        try (var inputStream = ossUploadService.getFileInputStream(ossUploadLog.getOssPath())) {
            byte[] bytes = inputStream.readAllBytes();
            // 3. 判断图片类型
            String fileName = ossUploadLog.getOssName();
            String contentType = "application/octet-stream";
            if (fileName != null) {
                String lower = fileName.toLowerCase();
                if (lower.endsWith(".png")) contentType = "image/png";
                else if (lower.endsWith(".jpg") || lower.endsWith(".jpeg")) contentType = "image/jpeg";
                else if (lower.endsWith(".bmp")) contentType = "image/bmp";
            }
            return ResponseEntity.ok()
                    .header("Content-Disposition", "inline; filename=\"" + fileName + "\"")
                    .header("Cache-Control", "no-cache, no-store, must-revalidate")
                    .header("Pragma", "no-cache")
                    .header("Expires", "0")
                    .contentType(org.springframework.http.MediaType.parseMediaType(contentType))
                    .body(bytes);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }
}
